package com.example.shushiyunsst.fragment.main.wallet.sub

import android.graphics.Color
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.fastjson.JSON
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.example.library_common.adapter.JssBaseQuickAdapter
import com.example.library_common.adapter.JssBaseViewHolder
import com.example.library_common.album.view.grid_view.XGridLayout
import com.example.library_common.album.view.grid_view.adapter.CommAdapter
import com.example.library_common.album.view.grid_view.adapter.XQuickViewHolder
import com.example.library_common.base.SimpleListFragment
import com.example.library_common.bean.CommonBean
import com.example.library_common.networking.RestClient
import com.example.shushiyunsst.R
import com.example.shushiyunsst.fragment.main.wallet.bean.MarketBean
import com.example.wallet.db.UserInfoManager
import com.google.android.material.tabs.TabLayout
import com.senon.modularapp.util.JssSpannableString
import ikidou.reflect.TypeBuilder
import java.lang.reflect.Type

class MarketFragment : SimpleListFragment<MarketBean>(), WalletLabInfo,
    OnItemChildClickListener {

    override val title: Int = R.string.market_title

    //全部
    private val all = 0

    //转账
    private val zhuangZhan = 15

    //推广
    private val tuiGuang = 23

    //节点收益
    private val jieDian = 19

    //权益分红
    private val liYiFenHong = 20

    //币商记录
    private val icon_seller_record = 10

    //母币记录
    private val mother_icon = 32

    //团购
    private val group_shopping=2

    //代理
    private val angency=3

    private val tabMap = mapOf(

        zhuangZhan to "转账",
//        tuiGuang to "推广分享",
//        jieDian to "节点收益",
//        liYiFenHong to "权益分红",
//        group_shopping to "团购记录",
//        angency to "代理"
//        icon_seller_record to "SST交易",
//        mother_icon to "母币记录"
    )

    private val tabMapTitleLine1 = mapOf(
        zhuangZhan to "转出链",
        tuiGuang to "累加链",
        jieDian to "累加链",
        liYiFenHong to "累加链",
        icon_seller_record to "钱包地址",
        mother_icon to "钱包地址"
    )

    private val tabMapTitleLine2 = mapOf(
        zhuangZhan to "转入链",
        tuiGuang to "发生链",
        jieDian to "发生链",
        liYiFenHong to "发生链",
        icon_seller_record to "",
        mother_icon to ""
    )

    private var queryType = all

    private lateinit var mLabRecyclerView: RecyclerView

    private var mLabeAdapter: JssBaseQuickAdapter<String>? = null


    companion object {
        fun newInstance(): MarketFragment {
            val args = Bundle()
            val fragment = MarketFragment()
            fragment.arguments = args
            return fragment
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isAddDividerItemDecoration = false
//        isEnableLoadMore = false
        mSuperBackPressedSupport = false
    }


    override fun initView(view: View) {
        super.initView(view)
        view.setBackgroundColor(Color.TRANSPARENT)
        mHeader.removeAllViews()
        addHeader(R.layout.market_header_fragment)

        mLabRecyclerView = view.findViewById(R.id.mRecyclerView)

        mLabRecyclerView.setHasFixedSize(true)

        mLabRecyclerView.layoutManager =
            LinearLayoutManager(_mActivity, LinearLayoutManager.HORIZONTAL, false)

        mLabeAdapter = object : JssBaseQuickAdapter<String>(R.layout.market_item_fragment) {
            override fun convert(holder: JssBaseViewHolder?, item: String?) {
                super.convert(holder, item)
                holder?.setText(R.id.mRTextView, item)
                    ?.setViewSelect(R.id.mRTextView, item == tabMap[queryType])

            }
        }
        mLabeAdapter?.addChildClickViewIds(R.id.mRTextView)
        mLabRecyclerView.adapter = mLabeAdapter

//        mLabeAdapter?.setOnItemChildClickListener { _, view, position ->
//            handOnItemChildClickListener(view, position)
//        }

        mLabeAdapter?.setOnItemChildClickListener(this)

        val ls = mutableListOf<String>()
        for (e in tabMap.entries) {
            ls.add(e.value)
        }
        mLabeAdapter?.setList(ls)
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        when(view.id){
            R.id.mRTextView->{
                handOnItemChildClickListener(view, position)
            }
        }
    }

    private fun handOnItemChildClickListener(view: View, position: Int) {
        val item = mLabeAdapter?.getItem(position)
        when (view.id) {
            R.id.mRTextView -> {
                mLabRecyclerView.scrollToPosition(position)
                var mQueryType = queryType

                for (e in tabMap.entries) {
                    if (item == e.value) {
                        mQueryType = e.key
                        break
                    }
                }

                if (mQueryType != queryType) {
                    queryType = mQueryType
                    if (!mSwipeRefreshLayout.isRefreshing) {
                        mSwipeRefreshLayout.isRefreshing = true
                    }
                    onRefresh()
                }

                mLabeAdapter?.notifyDataSetChanged()
            }
        }
    }


    override fun getItemLayout(): Int {
        return R.layout.market_fragment_layout
    }

    override fun refreshData() {
        if (isLoaded){
            if (!mSwipeRefreshLayout.isRefreshing) {
                mSwipeRefreshLayout.isRefreshing = true
            }
            onRefresh()
        }

    }

    override fun convertItem(helper: JssBaseViewHolder?, item: MarketBean?) {
        val titleTemplate = tabMap[item?.optType]
//        val titleTemplate =item?.typeDesc

        val titleLine1 = tabMapTitleLine1[item?.optType]
        val titleLine2 = tabMapTitleLine2[item?.optType]

        val line1Value = if (item?.fromAddress.isNullOrEmpty())
            item?.walletAddress
        else
            item?.fromAddress

        val str = "矿工费 ${item?.txFee} ${item?.tokenType}"
        val timeTv = if ((item?.txFee
                ?: 0.0) > 0.0
        ) JssSpannableString(_mActivity, "$str ${item?.createTime}")
            .first(str)
            .textColor(R.color.PrimaryColor)
        else item?.createTime

        helper?.setText(R.id.title_template, titleTemplate)
            ?.setText(R.id.valueTv, "${item?.txNums}")
            ?.setText(R.id.title_line_1, titleLine1)
            ?.setText(R.id.title_line_2, titleLine2)
            ?.setText(R.id.title_line_1_value, "$line1Value")
            ?.setText(R.id.title_line_2_value, "${item?.toAddress}")
            ?.setText(R.id.title_line_value_3, "${item?.typeDesc}")
            ?.setViewVisible(R.id.line_2, item?.toAddress?.isNotEmpty() == true)
//            ?.setText(R.id.title_line_1_value, "${item?.walletAddress}")
            ?.setText(R.id.title_line_4_value, "${item?.tokenType}")
            ?.setText(R.id.timeTv, timeTv)
            ?.setGone(
                R.id.line_1,
                item?.optType==group_shopping
                        ||item?.optType==angency
            )
    }

    override fun getListType(): Type {
        return TypeBuilder.newInstance(CommonBean::class.java)
            .beginSubType(List::class.java)
            .addTypeParam(MarketBean::class.java)
            .endSubType().build()
    }

    override fun netRequest() {

//        parseDate("")

        val userInfo = UserInfoManager.userInfoManager.getUserInfoWrapper()?.userInfo
        val map = mapOf(
            "pageCount" to 10,
            "pageIndex" to pageIndex,
            "queryType" to queryType,
            "uid" to userInfo?.uid
        )

        RestClient.builder()
            .url(R.string.queryBalanceLog)
            .raw(JSON.toJSONString(map))
            .success { parseDate(it) }
            .error { _, _ -> onFailed() }
            .failure { onFailed() }
            .build().post()
    }

    override fun parseDate(data: String?) {
//        super.parseDate(data)
        val obj = JSON.parseObject(data)
        val list = obj["list"] ?: ""
        val array = JSON.parseArray(JSON.toJSONString(list), MarketBean::class.java)
        loadListDate(array)
    }


}